package Test;

public class Test4 {
    volatile static int count = 0;
    static Object object = new Object();//锁对象

    //三个线程,abc,打印自己的线程名称并保证顺序是cba
    public static void main(String[] args) {
        Thread A = new Thread(()->{
            while (true){

                synchronized (object){
                    //唤醒其余两个线程
                    object.notifyAll();

                    if(count % 3 == 0) {
                        System.out.print(Thread.currentThread().getName());
                        //当我打印之后就不需要占有这把锁就可以wait了
                        count++;
                        try {
                            object.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        },"C");
        Thread B = new Thread(()->{
            while (true){
                synchronized (object){
                    //唤醒其余两个线程
                    object.notifyAll();

                    if(count % 3 == 1){
                        System.out.print(Thread.currentThread().getName());
                        //当我打印之后就不需要占有这把锁就可以wait了
                        count++;
                        try {
                            object.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        },"B");
        Thread C = new Thread(()->{
            while (true){
                synchronized (object){
                    //唤醒其余两个线程
                    object.notifyAll();

                    if(count % 3 == 2) {
                        System.out.println(Thread.currentThread().getName());
                        //当我打印之后就不需要占有这把锁就可以wait了
                        count++;
                        try {
                                object.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        },"A");
        //按顺序打印abc
        //可以采用定时器嘛,定时器是输入指定时间,当该时间到的时候才执行,
        A.start();
        B.start();
        C.start();
    }
}
